package com.donger.business.modules.upms.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donger.business.modules.upms.entity.SysPermission;
import com.donger.business.modules.upms.enums.MenuTypeEnum;
import com.donger.business.modules.upms.mapper.SysPermissionMapper;
import com.donger.business.modules.upms.service.ISysPermissionService;
import com.donger.common.core.constant.CommonConstants;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author xyx
 * @since 2019-01-12
 */
@SuppressWarnings("unchecked")
@AllArgsConstructor
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {

    @Override
    public List<SysPermission> findMenuByRoleId(Long roleId) {
        return baseMapper.listMenusByRoleId(roleId);
    }

    /**
     * 查询非按钮菜单
     *
     * @return 非按钮菜单列表
     */
    @Override
    public List<SysPermission> queryNotButtonList() {
        return this.list(Wrappers.<SysPermission>lambdaQuery().ne(SysPermission::getType, MenuTypeEnum.BUTTON.getValue()));
    }

    /**
     * 查询子菜单
     *
     * @param menuId 父ID
     * @return 子菜单列表
     */
    @Override
    public List<SysPermission> queryListParentId(Long menuId) {
        return this.list(Wrappers.<SysPermission>lambdaQuery().eq(SysPermission::getParentId, menuId));
    }

    /**
     * 根据当前用户查询系统菜单
     *
     * @param currentUserId 当前用户ID
     * @return 系统菜单列表
     */
    @Override
    /*@Cacheable(value = "menu_details", key = "#currentUserId + '_menu'")*/
    public List<SysPermission> getUserMenuList(Long currentUserId) {
        //系统管理员，拥有最高权限
        if (CommonConstants.SUPER_ADMIN.equals(currentUserId)) {
            return recursiveBuildTree(baseMapper.selectList(null), SysPermission.LEVEL_ONE_MENU);
        }
        return recursiveBuildTree(baseMapper.queryMenuByUserId(currentUserId), SysPermission.LEVEL_ONE_MENU);
    }


    /**
     * 递归建树
     *
     * @param sysMenuList 查询出的菜单数据
     * @param parentId    父节点ID
     * @return 递归后的树列表
     */
    private List<SysPermission> recursiveBuildTree(List<SysPermission> sysMenuList, Long parentId) {
        List<SysPermission> childList = sysMenuList.stream().filter(m -> m.getParentId().equals(parentId)).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(childList)) {
            return null;
        }
        for (SysPermission sysMenu : childList) {
            sysMenu.setChildren(recursiveBuildTree(sysMenuList, sysMenu.getId()));
        }
        return childList;
    }
}
